package com.example.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ：baohuajie
 * @description ：线程池配置
 * @date ：2020-07-31
 */
@Configuration
public class ThreadPoolConfig {

    @Value("${thread.corePoolSize}")
    private int corePoolSize;

    @Value("${thread.maxPoolSize}")
    private int maxPoolSize;

    @Value("${thread.keepAliveSeconds}")
    private int keepAliveSeconds;

    @Value("${thread.queueCapacity}")
    private int queueCapacity;

    private final String threadNamePrefixSet = "Spring-ThreadPool#";

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 线程池维护线程的最少数量
        executor.setCorePoolSize(corePoolSize);
        // 线程池维护线程的最大数量
        executor.setMaxPoolSize(maxPoolSize);
        // 空闲线程的最长保留时间,超过此时间空闲线程会被回收
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程池所使用的缓冲队列
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefixSet);
        // rejection-policy：当线程池线程已达到最大值且任务队列也满了的情况下，如何处理新任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return executor;
    }

}
